package com.cyzy.controller;

import com.cyzy.entity.ClassDO;
import com.cyzy.entity.RequestDTO;
import com.cyzy.entity.User;
import com.cyzy.service.UserService;
import com.cyzy.util.JwtUtil;
import com.cyzy.util.MinioUtil;
import org.mybatis.logging.Logger;
import org.mybatis.logging.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Map;
import java.util.HashMap;

@RestController
@RequestMapping("/user")
@CrossOrigin(origins = "*")
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private JwtUtil jwtUtil;

    private static final Logger log = LoggerFactory.getLogger(UserController.class);
    private final MinioUtil minioUtil;

    @Autowired
    public UserController(MinioUtil minioUtil) {
        this.minioUtil = minioUtil;
    }
    /**
     * 用户登录
     * 兼容前端 GET 调用
     */
    @RequestMapping(value = "/login", method = {RequestMethod.POST, RequestMethod.GET})
    public RequestDTO login(@RequestParam String username, @RequestParam String password) {
        try {
            String token = userService.loginByUsername(username, password);
            if (token != null) {
                // 获取用户信息
                User user = userService.findByUsername(username);
                Map<String, Object> loginResult = new HashMap<>();
                loginResult.put("token", token);
                loginResult.put("userId", user.getId());
                loginResult.put("username", user.getUsername());
                loginResult.put("nickname", user.getNickname());
                loginResult.put("role", user.getRole());
                loginResult.put("roleText", user.getRole() == 1 ? "教师" : "学生");
                loginResult.put("classId", user.getClassId());
                return new RequestDTO(200, "登录成功", loginResult);
            }
            return new RequestDTO(500, "登录失败", null);
        } catch (Exception e) {
            return new RequestDTO(500, e.getMessage(), null);
        }
    }
    
    /**
     * 用户注册
     */
    @PostMapping("/register")
    public RequestDTO register(@RequestBody User user) {
        try {
            String result = userService.registerUser(user);
            if (result != null) {
                Map<String, Object> registerResult = new HashMap<>();
                registerResult.put("username", result);
                registerResult.put("message", "注册成功，请登录");
                
                return new RequestDTO(200, "注册成功", registerResult);
            }
            return new RequestDTO(500, "注册失败", null);
        } catch (Exception e) {
            return new RequestDTO(500, e.getMessage(), null);
        }
    }
    //修改信息
    @PostMapping("/update")
    public RequestDTO update(@RequestBody  User user) {
        int i = userService.updateUser(user);
        if (i > 0){
            return new RequestDTO(200,"修改成功",null);
        }
        return new RequestDTO(200,"修改失败",null);
    }
    @RequestMapping("/validate")
    public ResponseEntity<?> validateToken(@RequestHeader("Authorization") String authHeader)
    {
        try {
            System.out.println("收到Authorization header: " + authHeader);
            
            String token = null;
            // 处理不同格式的Authorization header
            if (authHeader != null && authHeader.startsWith("Bearer ")) {
                token = authHeader.substring(7);
            } else if (authHeader != null && authHeader.startsWith("bearer ")) {
                token = authHeader.substring(7);
            } else {
                token = authHeader; // 如果没有Bearer前缀，直接使用
            }
            
            System.out.println("提取的token: " + token);
            
            if (token == null || token.trim().isEmpty()) {
                return ResponseEntity.ok(new RequestDTO(500, "Token is empty", null));
            }
            
            if (jwtUtil.validateToken(token)){
                Integer userId = jwtUtil.getUserIdFromToken(token);
                System.out.println("Token验证成功，用户ID: " + userId);
                return ResponseEntity.ok(new RequestDTO(200, "Token is valid", userId));
            } else {
                System.out.println("Token验证失败");
                return ResponseEntity.ok(new RequestDTO(500, "Token is invalid", null));
            }
        } catch (Exception e) {
            System.out.println("Token验证异常: " + e.getMessage());
            e.printStackTrace();
            return ResponseEntity.ok(new RequestDTO(500, "Token validation error: " + e.getMessage(), null));
        }
    }
    @RequestMapping("/find-by-id")
    public RequestDTO findById(String id) {
        User user = userService.findById(id);
        return new RequestDTO(200,"查询成功",user);
    }
    
    /**
     * 获取个人信息
     */
    @GetMapping("/profile/{id}")
    public RequestDTO getUserProfile(@PathVariable String id) {
        try {
            User user = userService.findById(id);
            // 隐藏敏感信息
            user.setPassword(null);
            return new RequestDTO(200, "获取个人信息成功", user);
        } catch (Exception e) {
            return new RequestDTO(500, e.getMessage(), null);
        }
    }
    
    /**
     * 更新个人信息
     */
    @PostMapping("/profile/update")
    public RequestDTO updateProfile(@RequestBody User user) {
        try {
            System.out.println("=====================================");
            int result = userService.updateUserProfile(user);
            if (result > 0) {
                return new RequestDTO(200, "个人信息更新成功", null);
            } else {
                return new RequestDTO(500, "更新失败", null);
            }
        } catch (Exception e) {
            return new RequestDTO(500, e.getMessage(), null);
        }
    }
    
    /**
     * 修改密码
     */
    @PostMapping("/change-password")
    public RequestDTO changePassword(@RequestParam String userId,
                                   @RequestParam String oldPassword,
                                   @RequestParam String newPassword) {
        try {
            boolean result = userService.changePassword(userId, oldPassword, newPassword);
            if (result) {
                return new RequestDTO(200, "密码修改成功", null);
            } else {
                return new RequestDTO(500, "密码修改失败", null);
            }
        } catch (Exception e) {
            return new RequestDTO(500, e.getMessage(), null);
        }
    }
    
    /**
     * 实名认证
     */
    @PostMapping("/verify-identity")
    public RequestDTO verifyIdentity(@RequestParam String userId,
                                   @RequestParam String realName,
                                   @RequestParam String idCard) {
        try {
            boolean result = userService.verifyIdentity(userId, realName, idCard);
            if (result) {
                return new RequestDTO(200, "实名认证成功", null);
            } else {
                return new RequestDTO(500, "实名认证失败", null);
            }
        } catch (Exception e) {
            return new RequestDTO(500, e.getMessage(), null);
        }
    }
    
    /**
     * 上传头像
     */
    @PostMapping("/upload-avatar")
    public RequestDTO uploadAvatar(@RequestParam String userId,
                                 @RequestParam String avatarUrl) {
        try {
            boolean result = userService.updateAvatar(userId, avatarUrl);
            if (result) {
                return new RequestDTO(200, "头像更新成功", avatarUrl);
            } else {
                return new RequestDTO(500, "头像更新失败", null);
            }
        } catch (Exception e) {
            return new RequestDTO(500, e.getMessage(), null);
        }
    }

    @PostMapping("/upload/single")
    public RequestDTO uploadSingleFile(
            @RequestParam String userId,
            @RequestParam("file") MultipartFile file) throws IOException {
//        log.info("接收单文件上传请求，文件名：{}，大小：{}KB",
//                file.getOriginalFilename(), file.getSize() / 1024);

        Map<String, Object> result = new HashMap<>(4);
        // 新增：限制文件大小（例如不超过10MB）
        long maxSize = 10 * 1024 * 1024; // 10MB
        if (file.getSize() > maxSize) {
            String errorMsg = "文件大小超过限制（最大10MB）";
//            log.warn(errorMsg);
            result.put("success", false);
            result.put("message", errorMsg);
        }

        String fileUrl = minioUtil.uploadMultipartFile(file);
        result.put("success", true);
        result.put("message", "文件上传成功");
        result.put("fileUrl", fileUrl);
        result.put("fileName", file.getOriginalFilename());
        boolean avatar = userService.updateAvatar(userId, fileUrl);
        if (avatar) {
            return new RequestDTO(200, "头像更新成功", fileUrl);
        } else {
            return new RequestDTO(500, "头像更新失败", null);
        }

    }
    
    /**
     * 获取用户统计信息
     */
    @GetMapping("/statistics/{userId}")
    public RequestDTO getUserStatistics(@PathVariable String userId) {
        try {
            Object statistics = userService.getUserStatistics(userId);
            return new RequestDTO(200, "获取统计信息成功", statistics);
        } catch (Exception e) {
            return new RequestDTO(500, e.getMessage(), null);
        }
    }

    /**
     * 加入班级申请
     */
    @RequestMapping("/join-class")
    public RequestDTO joinClass(@RequestParam String userId,@RequestParam String classId){
            System.out.println(userId+classId);
            int result = userService.joinClass(userId, classId);
            if (result > 0) {
                return new RequestDTO(200, "申请提交成功", null);
            } else if (result == -1) {
                return new RequestDTO(400, "请勿重复申请", null);
            } else {
                return new RequestDTO(500, "申请提交失败", null);
            }
    }

    @RequestMapping("/join-classCode")
    public RequestDTO joinClassByCode(@RequestParam String userId, @RequestParam String classCode) {
        int result = userService.joinClassByCode(userId, classCode);
        System.out.println(userId+classCode);
        if (result > 0) {
            String classId = userService.findClassIdByCode(classCode);
            return new RequestDTO(200, "加入班级成功", classId);
        } else if (result == -1) {
            return new RequestDTO(400, "班级码无效", null);
        } else {
            return new RequestDTO(500, "加入班级失败", null);
        }
    }

    //查询班级信息
    @RequestMapping("/class/info")
    public RequestDTO getClassInfo(@RequestParam String classCode) {
        if (classCode == null || classCode.isEmpty()) {
            return new RequestDTO(400, "未加入班级", null);
        }
        ClassDO classDO = userService.findClassById(classCode);
        if (classDO == null) {
            return new RequestDTO(404, "班级不存在", null);
        }
        return new RequestDTO(200, "查询成功", classDO);
    }
    //查询班级Id
    @RequestMapping("/class/id")
    public RequestDTO getClassId(@RequestParam String userId) {
        int classId = userService.getClassId(userId);
        return new RequestDTO(200, "查询成功", classId);

    }
}
